package com.ytjj.qmyx.mall.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.model.Product;
import com.ytjj.qmyx.mall.model.dto.AppNewLifeHallIndexGroupProductDto;
import com.ytjj.qmyx.mall.model.dto.AppNewLifeHallIndexOldForNewProductDto;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.service.ActivityService;
import com.ytjj.qmyx.mall.service.EvaluationServive;
import com.ytjj.qmyx.mall.service.GroupActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生活馆接口
 *
 */
@RestController
@RequestMapping("/life/hall")
@Slf4j
public class NewLifeHallIndexController {
    @Resource
    private ActivityService activityService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysConfigUtil sysConfigUtil;
    @Resource
    private EvaluationServive evaluationServive;
    @Autowired
    private GroupActivityService groupActivityService;

    /**
     * 首页数据
     * @return
     * 数据来源:
     * 优惠券=红包中心
     * 卡券兑换=积分兑换
     * 补贴=运营活动->品牌补贴
     *
     * 运营管理->板块管理
     *
     * @param columnId 活动栏目id
     */
    @GetMapping("/index")
    public CommonResult index(@RequestParam(required = false) Integer columnId) {
        //1.拼团数据 取4条 这里只需要返回拼团的商品图片和id  每5分钟刷新缓存
        List<AppNewLifeHallIndexGroupProductDto> groupDatas = doGroupDatas();
        //2.所有补贴数据 每次取3条
        List<AppNewLifeHallIndexOldForNewProductDto> oldForNewDatas = doOldForNewDatas();
        //3.下面四项数据 包含活动数据和板块数据
        List<AppNewLifeHallActivityResponse> activityList = new ArrayList<>();
        activityList = doFourDatasByActivity(activityList);
        activityList = doFourDatasByForum(activityList);

        NewLifeHallIndexResponse response = new NewLifeHallIndexResponse();
        response.setGroupDatas(groupDatas);
        response.setOldForNewDatas(oldForNewDatas);
        response.setFourDatas(activityList);
        return CommonResult.success(response);
    }

    /**
     * 板块数据
     * @param activityList
     * @return
     */
    public List<AppNewLifeHallActivityResponse> doFourDatasByForum(List<AppNewLifeHallActivityResponse> activityList) {
        String forumLiveIdStr = redisService.get(RedisConstants.CONFIG_FORUM_APP);
        String[] configForumIds = forumLiveIdStr.split(",");
        Arrays.stream(configForumIds).forEach(forumId -> {
            List<ForumLiveInfoResponse> fix_list = (List<ForumLiveInfoResponse>) evaluationServive.getForumLiveInfoList(Integer.parseInt(forumId), 0,2, TokenUtil.getPlatformData());
            String title = redisService.get(RedisConstants.PRODUCT_FORUM_TITLE + forumId);
            String img = redisService.get(RedisConstants.PRODUCT_FORUM_IMG + forumId);
            String desc = redisService.get(RedisConstants.PRODUCT_FORUM_DESC + forumId);
            AppNewLifeHallActivityResponse response = new AppNewLifeHallActivityResponse();
            response.setForumId(Integer.parseInt(forumId));
            response.setTitle(title);
            response.setImgUrl(img);
            response.setDesc(desc);
            response.setItems(new ArrayList<>());

            fix_list.stream().forEach(product -> {
                AppNewLifeHallIndexOldForNewProductDto productDto = new AppNewLifeHallIndexOldForNewProductDto();
                productDto.setId(product.getId());
                productDto.setProductName(product.getProductName());
                productDto.setProductImg(product.getProductImg());
                productDto.setOriginalPrice(product.getOriginalPrice());
                productDto.setPrice(product.getPrice());
                response.getItems().add(productDto);
            });
            activityList.add(response);
        });
        return activityList;
    }

    /**
     * 活动数据
     * @param activityList
     * @return
     */
    public List<AppNewLifeHallActivityResponse> doFourDatasByActivity(List<AppNewLifeHallActivityResponse> activityList) {
        String configActivityTypeStr = redisService.get(RedisConstants.CONFIG_ACTIVITYTYPES_APP);
        String[] configActivityTypes = configActivityTypeStr.split(",");
        Arrays.stream(configActivityTypes).forEach(type -> {
            List<Product> activityProducts = activityService.getProductByActivityType(type, 2);
            String title = redisService.get(RedisConstants.PRODUCT_ACTIVITY_TITLE + type);
            String img = redisService.get(RedisConstants.PRODUCT_ACTIVITY_IMG + type);
            String desc = redisService.get(RedisConstants.PRODUCT_ACTIVITY_DESC + type);
            AppNewLifeHallActivityResponse response = new AppNewLifeHallActivityResponse();
            response.setActivityType(type);
            response.setTitle(title);
            response.setImgUrl(img);
            response.setDesc(desc);
            response.setItems(new ArrayList<>());
            activityProducts.stream().forEach(product -> {
                AppNewLifeHallIndexOldForNewProductDto productDto = new AppNewLifeHallIndexOldForNewProductDto();
                productDto.setId(product.getId());
                productDto.setProductName(product.getProductName());
                productDto.setProductImg(product.getProductImg());
                productDto.setSceneImg(product.getSceneImg());
                productDto.setOriginalPrice(product.getOriginalPrice());
                productDto.setActivityMax(product.getActivityMax());
                productDto.setPrice(product.getPrice());
                productDto.setStock(product.getStock());
                productDto.setDiffPrice(product.getPrice().subtract(product.getActivityMax()));
                response.getItems().add(productDto);
            });
            activityList.add(response);
        });
        return activityList;
    }

    /**
     * 获取拼团数据
     * @return
     */
    public List<AppNewLifeHallIndexGroupProductDto> doGroupDatas() {
        String curPositionHaveRecord = redisService.get(RedisConstants.CUR_GROUP_DATAS_HAVEVALUE);//获取当前分段中是否还有数据 1-有数据,表示不需要重新从数据库中获取
        if (!StringUtils.isEmpty(curPositionHaveRecord) && curPositionHaveRecord.equals("1")) {
            Set<Object> curPositionDataList = redisService.sGet(RedisConstants.CUR_GROUP_DATAS);
            List<AppNewLifeHallIndexGroupProductDto> results = new LinkedList<>();//当前分段中补贴商品数据
            if (!CollectionUtils.isEmpty(curPositionDataList)) {
                curPositionDataList.stream().forEach(s -> {
                    JSONObject objJsonStr = JSON.parseObject(s.toString());
                    AppNewLifeHallIndexGroupProductDto dto = JSONObject.toJavaObject(objJsonStr, AppNewLifeHallIndexGroupProductDto.class);
                    results.add(dto);
                });
            }
            return results;
        }
        String curPositionStr = redisService.get(RedisConstants.CUR_POSITION_INDEX_GROUP);
        Integer curPosition = 0;
        if (StringUtils.isEmpty(curPositionStr)) {
            curPosition = 0;
            redisService.set(RedisConstants.CUR_POSITION_INDEX_GROUP, String.valueOf(curPosition));
        }else {
            curPosition = Integer.parseInt(curPositionStr) + 1;
            String pageTotalStr = redisService.get(RedisConstants.GROUP_PAGES);
            Integer pageTotal = Integer.parseInt(pageTotalStr);
            if (curPosition > pageTotal) {
                curPosition = 0;
            }
            redisService.set(RedisConstants.CUR_POSITION_INDEX_GROUP, String.valueOf(curPosition));
        }
        Integer pageNum = curPosition;
        Integer pageSize = 4;
        List<AppNewLifeHallIndexGroupProductDto> groupProductDatas = groupActivityService.queryFineGroupListByNewLifeHall(pageNum, pageSize);
        return groupProductDatas;
    }

    /**
     * 获取红包数据
     * @return
     */
    public List<ProductResponse> doCouponDatas() {
        List<ProductResponse> couponList = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_COUPON.name() + TokenUtil.getPlatformData();
        String result = redisService.get(key);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(result)) {
            try {
                couponList = JSONArray.parseArray(result, ProductResponse.class);
            } catch (Exception e) {
                log.info("优惠券序列化异常：", e);
                couponList = activityService.getCouponList();
                redisService.set(key, JSON.toJSONString(couponList));
                redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
            }
        } else {
            couponList = activityService.getCouponList();
            redisService.set(key, JSON.toJSONString(couponList));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return couponList.stream().limit(2).collect(Collectors.toList());
    }

    /**
     * 获取补贴数据
     * @return
     */
    public List<AppNewLifeHallIndexOldForNewProductDto> doOldForNewDatas() {
        String curPositionHaveRecord = redisService.get(RedisConstants.CUR_POSITION_DATAS_HAVEVALUE);//获取当前分段中是否还有数据 1-有数据,表示不需要重新从数据库中获取
        if (!StringUtils.isEmpty(curPositionHaveRecord) && curPositionHaveRecord.equals("1")) {
            Set<Object> curPositionDataList = redisService.sGet(RedisConstants.CUR_POSITION_DATAS);
            List<AppNewLifeHallIndexOldForNewProductDto> results = new LinkedList<>();//当前分段中补贴商品数据
            if (!CollectionUtils.isEmpty(curPositionDataList)) {
                curPositionDataList.stream().forEach(s -> {
                    JSONObject objJsonStr = JSON.parseObject(s.toString());
                    AppNewLifeHallIndexOldForNewProductDto dto = JSONObject.toJavaObject(objJsonStr, AppNewLifeHallIndexOldForNewProductDto.class);
                    results.add(dto);
                });
            }
            return results;
        }
        String curPositionStr = redisService.get(RedisConstants.CUR_POSITION_INDEX_OLDFORNEW);
        Integer curPosition = 0;
        if (StringUtils.isEmpty(curPositionStr)) {
            curPosition = 0;
            redisService.set(RedisConstants.CUR_POSITION_INDEX_OLDFORNEW, String.valueOf(curPosition));
        }else {
            curPosition = Integer.parseInt(curPositionStr) + 1;
            String pageTotalStr = redisService.get(RedisConstants.OLD_FOR_NEW_PAGES);
            Integer pageTotal = Integer.parseInt(pageTotalStr);
            if (curPosition > pageTotal) {
                curPosition = 0;
            }
            redisService.set(RedisConstants.CUR_POSITION_INDEX_OLDFORNEW, String.valueOf(curPosition));
        }
        Integer pageNum = curPosition;
        Integer pageSize = 3;
        List<AppNewLifeHallIndexOldForNewProductDto> list = activityService.getAllList(pageNum, pageSize, null);
        return list;
    }
}
